import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64

# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 绑定地址和端口
server_address = ('172.20.10.5', 8888)
server_socket.bind(server_address)

# 监听连接
server_socket.listen(1)
print('服务器正在监听 {}:{}'.format(*server_address))

# 接受客户端连接
client_socket, client_address = server_socket.accept()
print('接受来自 {} 的连接'.format(client_address))

# AES 加密配置（需与客户端一致）
key = b'ThisIsASecretKey'  # 32字节密钥
iv = b'ThisIsAnIV4567890'  # 16字节初始化向量

def decrypt_data(ciphertext):
    ciphertext = base64.b64decode(ciphertext)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
    return plaintext.decode('utf-8')

while True:
    # 接收加密数据
    encrypted_data = client_socket.recv(1024).decode('utf-8')
    if not encrypted_data:
        break
    
    # 解密并写入文件
    decrypted_data = decrypt_data(encrypted_data)
    with open('server_received.txt', 'w') as f:
        f.write(decrypted_data)
    print(f"已接收并解密数据，保存至 server_received.txt")

    # 从文件读取响应内容
    with open('server_response.txt', 'r') as f:
        response = f.read()
    
    # 加密并发送响应
    cipher = AES.new(key, AES.MODE_CBC, iv)
    ct_bytes = cipher.encrypt(pad(response.encode(), AES.block_size))
    encrypted_response = base64.b64encode(ct_bytes).decode('utf-8')
    client_socket.send(encrypted_response.encode('utf-8'))
    if input("是否要继续？Y/N")=="N":
        break

# 关闭连接
client_socket.close()
server_socket.close()